//
//  AuthenPhotoVM.swift
//  kxf
//
//  Created by Mac on 2024/3/6.
//

import Foundation
import UIKit
import Photos
import MCToast

enum PHOTOTYPE {
    case mentou
    case diannei
    case cash
    case dianwai
    case idCardFront
    case idCardBack
    case idCardInHand
    case bankFront
    case kaihuxuke
    case zhuanzhangshenqing
    case other
    case licence
    case mentouCompany
    case cashCompany
    case dianneiCompany
    case dianwaiCompany
    case location
    case proofMchnt
}

class AuthenPhotoVM: UIView {
    
    let selfHeight = kFitWidth(171)
    
    var isRead = false
    var controller = WHBaseViewVC()
    
    var photoBlock:(()->())?
    var exampleBlock:(()->())?

    override init(frame:CGRect){
        super.init(frame: CGRect.init(x: frame.origin.x, y: frame.origin.y, width: SCREEN_WIDHT*0.5, height: selfHeight))
        self.backgroundColor = .white
        self.isUserInteractionEnabled = true
        
        initUI()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var imgView : UIImageView = {
        let img = UIImageView()
        img.layer.cornerRadius = kFitWidth(12)
        img.contentMode = .scaleAspectFit
        img.clipsToBounds = true
        img.isUserInteractionEnabled = true
        img.backgroundColor = WHColorWithAlpha(colorStr: "F10E0E", alpha: 0.08)
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(photoTapAction))
        img.addGestureRecognizer(tap)
        
        return img
    }()
    lazy var addIconImg : UIImageView = {
        let img = UIImageView()
        img.image = UIImage.init(named: "authen_photo_add")
        img.isUserInteractionEnabled = true
        
        return img
    }()
    lazy var titleLabel : UILabel = {
        let lab = UILabel()
        lab.textColor = .black
        lab.font = .systemFont(ofSize: 14, weight: .medium)
        lab.textAlignment = .center
        lab.adjustsFontSizeToFitWidth = true
        return lab
    }()
    lazy var exampleImgView : UIImageView = {
        let img = UIImageView()
        img.image = UIImage.init(named: "authen_example_icon")
        
        return img
    }()
    lazy var exampleLabel : UILabel = {
        let lab = UILabel()
        lab.textColor = .black
        lab.font = .systemFont(ofSize: 12, weight: .medium)
        lab.text = "查看示例"
        
        return lab
    }()
    lazy var exampleTapView : UIView = {
        let vi = UIView()
        vi.backgroundColor = .clear
        vi.isUserInteractionEnabled = true
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(exampleTapAction))
        vi.addGestureRecognizer(tap)
        
        return vi
    }()
}

extension AuthenPhotoVM{
    @objc func photoTapAction() {
        if self.photoBlock != nil{
            self.photoBlock!()
        }
    }
    @objc func exampleTapAction() {
        if self.isRead == true{
//            if self.saveBlock != nil{
//                self.saveBlock!()
//            }
            self.saveAction()
        }else{
            if self.exampleBlock != nil{
                self.exampleBlock!()
            }
        }
    }
    func setImgUrl(urlstring:String){
        if urlstring.count > 5{
            self.addIconImg.isHidden = true
            self.titleLabel.isHidden = true
            self.imgView.setImgUrl(urlString: urlstring)
        }
    }
    func setReadMode() {
        self.isRead = true
        exampleImgView.setImgLocal(imgName: "authen_save_icon")
        exampleLabel.text = "保存到相册"
        imgView.isUserInteractionEnabled = false
    }
}
extension AuthenPhotoVM{
    @objc func saveAction() {
        PHPhotoLibrary.requestAuthorization { (status) in
            DispatchQueue.main.async {
                if status == .restricted || status == .denied{
                    MCToast.mc_text("无访问相册权限，请前往【设置】->【星渝付助手】打开相册访问权限")
//                    self.controller.presentAlertVc(confirmBtn: "打开", message: "无访问相册权限，是否去打开权限?", title: "提示", cancelBtn: "取消", handler: { (actions) in
//                        let url = NSURL.init(string: UIApplication.openSettingsURLString)
//                        if UIApplication.shared.canOpenURL(url! as URL){
//                            UIApplication.shared.openURL(url! as URL)
//                        }
//                    }, viewController: self.controller)
                }else{
                    MCToast.mc_loading(autoClearTime: 30)
                    let image = self.imgView.image
                    UIImageWriteToSavedPhotosAlbum(image ?? self.imgView.mc_makeImage(), self, #selector(self.saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
                }
            }
        }
    }
    @objc private func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject){
        MCToast.mc_remove()
        if error != nil{
            MCToast.mc_text("保存失败。")
        }else{
            MCToast.mc_text("已保存到系统相册")
        }
    }
}
extension AuthenPhotoVM{
    func initUI() {
        addSubview(imgView)
        imgView.addSubview(addIconImg)
        imgView.addSubview(titleLabel)
        addSubview(exampleLabel)
        addSubview(exampleImgView)
        addSubview(exampleTapView)
        
        setConstrait()
    }
    func setConstrait() {
        imgView.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.top.equalTo(kFitWidth(10))
            make.width.equalTo(kFitWidth(168))
            make.height.equalTo(kFitWidth(118))
        }
        addIconImg.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.top.equalTo(kFitWidth(10))
            make.width.height.equalTo(kFitWidth(70))
        }
        titleLabel.snp.makeConstraints { make in
//            make.centerX.lessThanOrEqualToSuperview()
            make.top.equalTo(kFitWidth(83))
            make.left.width.equalToSuperview()
        }
        exampleImgView.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(59))
            make.width.height.equalTo(kFitWidth(22))
            make.top.equalTo(imgView.snp.bottom).offset(kFitWidth(12))
        }
        exampleLabel.snp.makeConstraints { make in
            make.centerY.lessThanOrEqualTo(exampleImgView)
            make.left.equalTo(exampleImgView.snp.right).offset(kFitWidth(3))
        }
        exampleTapView.snp.makeConstraints { make in
            make.left.equalTo(exampleImgView).offset(kFitWidth(-20))
            make.right.equalTo(exampleLabel).offset(kFitWidth(20))
            make.top.equalTo(imgView.snp.bottom)
            make.bottom.equalToSuperview()
        }
    }
}
